articles

Home / DeveloperSection / Articles / Collections in C#

Collections in C#

Anchal Kesharwani7164 25-Jun-2014

In this article, I’m explaining the concept of collection classes.

In C#, a collection is a group of objects. Collection represents the set of objects Collection classes are used for data storage and manipulate the data. Collections are data structures that holds data in different ways for flexible operations.

The .NET contains large number of classes and interfaces. The base of each class is the object class. All the collections implement IEnumerable interface that is extended by ICollection interface. IDictionary and IList are also interfaces for collection which are derived from ICollection as shown in below figure.

Collections in C#

Main collection classes which are used in c#

  •      ArrayList Class
  •      List Class
  •      HashTable Class
  •      Stack Class
  •      Queue class
ArrayList

An ArrayList is a collection from a standard System.Collections namespace. ArrayList implements the IList interface using an array whose size is dynamically increased as required. The datatype of an ArrayList is object type, so we can add the elements having the datatype string, integer and any other.

Example 1
using System;
using System.Collections;
namespace ArrayListExample
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList arr = new ArrayList(); // create array list object
            arr.Add("January");             //  add arraylist items
            arr.Add("Februrary");
            arr.Add("March");
            arr.Add("April");
            arr.Add("May");
            arr.Add("June");
            arr.Add("July");
            arr.Add("August");
            arr.Add("September");
            arr.Add("October");
            arr.Add("November");
            arr.Add("December");
            Console.WriteLine("The elements of the ArrayList are:");
            foreach (object obj in arr)
            {
                Console.WriteLine(obj);
               
            }
            Console.WriteLine("Array capacity :" + arr.Capacity); // it define the cpacity of arraylist
            Console.WriteLine("Array element count :" +arr.Count); // count the arraylist item
            Console.ReadKey();      // hold the console screen
        }
    }
}
 Output

Collections in C#

In this example, how to add element in arraylist and how to use its property.

List
The List class in .NET represents a strongly typed list of objects that can be accessed by index. The List<T> class is contained with the System.Collections.Generic namespace whilst the ArrayList class is contained within theSystem.Collections namespace.The List provides the built-in methods and properties including add, remove, search, and sort.
Example
using System;
using System.Collections.Generic;
 
namespace ListExample
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> title = new List<string>();  // create a list object
            Console.WriteLine("\nCapacity: {0}", title.Capacity);
            title.Add("Array List");        // add list items
            title.Add("List");
            title.Add("HashTable");
            title.Add("Stack");
            title.Add("Queue");
            Console.WriteLine();
            foreach (string author in title)
            {
                Console.WriteLine(author);          // print list data
            }
            Console.WriteLine("Number of Titles in List: {0}", title.Count);
            Console.WriteLine("\nContains(\"Title\"): {0}",
                title.Contains("Abstract class")); //contain method return true or false
            Console.WriteLine("\nInsert(2, \"Static class\")");
            title.Insert(2, "Non-static class");    // insert new item at position 2
            Console.WriteLine();
            foreach (string author in title)
            {
                Console.WriteLine(author);
            }
            Console.WriteLine("\ntitle[3]: {0}", title[3]);
            Console.WriteLine("\nRemove(\"Static class\")");
            title.Remove("Array List");             // remove item
            Console.WriteLine();
            foreach (string author in title)
            {
                Console.WriteLine(author);
            }
            Console.WriteLine();
            title.Sort();           // sort the list
            Console.WriteLine("Sorted List");
            foreach (string author in title)
            {
                Console.WriteLine(author);
            }
            title.TrimExcess();
            Console.WriteLine("\nTrimExcess()");
            Console.WriteLine("Capacity: {0}", title.Capacity); //list capacity
            Console.WriteLine("Count: {0}", title.Count);       // list element count
            title.Clear();      // list clear
            Console.WriteLine("\nClear()");
            Console.WriteLine("Capacity: {0}", title.Capacity);  // after clearing the list
            Console.WriteLine("Count: {0}", title.Count);       // after clearing the list item 0
            Console.ReadKey();
        }
    }
}

 

Output

Collections in C#

In this example, we use the list functions. 

HashTable

The Hashtable class represents a collection of “key-and-value pairs” that are organized based on the hash code of the key. Hashtable is like as dictionary. Any non-null object can be used as a key but a value can. We can retrieve items from hashTable to provide the key .

Example
using System;
using System.Collections;
 
namespace HashTableExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Hashtable hashTableObj = new Hashtable();
            hashTableObj.Add(1, 10);    // hastable add integer key
            hashTableObj.Add(2.99, 20); // hastable add float key
            hashTableObj.Add('A'"Alphabet");  // hastable add character key
            hashTableObj.Add("Country""India");  // hastable add string key
 
            Console.WriteLine(hashTableObj[1].ToString());   // print data where the key is find
            Console.WriteLine(hashTableObj[2.99].ToString());
            Console.WriteLine(hashTableObj['A'].ToString());
            Console.WriteLine(hashTableObj["Country"].ToString());
 
            Console.WriteLine(hashTableObj.ContainsValue("India")); // contain value method return true or false
            Console.WriteLine(hashTableObj.ContainsKey(1));         // contain Key method return true or false
            Console.WriteLine("Hashtable element Count :" + hashTableObj.Count);  // hastable element count
            hashTableObj.Clear();
            Console.WriteLine("Hashtable element Count :" + hashTableObj.Count);  // after clear hastable element count
            Console.ReadKey(); // hold the screen
        }
    }
}

 

Output

Collections in C#

In this example, hashtable add, clear,contain and more used. 


Stack


Stack is the LIFO (Last-In-first-out) collection. Stack contains the push-pop

method.In stack, we can insert (push) and retrieve (pop) from the stack list. Stack

class is under the System.Collections.Generic namespace.

 

Example
using System;
using System.Collections.Generic;
 
namespace StackClassExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Stack<int> stackObj=new Stack<int>(); // create an object of Stack class
            // Stack stackObj=new Stack(); // or you create this type stack class object
            stackObj.Push(100);     // add or push the item into Stack
            stackObj.Push(200);
            stackObj.Push(300);
            stackObj.Push(400);
            stackObj.Push(500);
            foreach (int i in stackObj)
            {
                Console.WriteLine(i);    // fetch or pop the item from Stack
            }
            Console.WriteLine("Stack last item:" + stackObj.Pop()); // fetch last element of stack
            Console.WriteLine("Stack item count:" + stackObj.Count); // count stack item
            Console.WriteLine("Stack item count:" + stackObj.Contains(100)); // stack contains this item
            stackObj.Clear();       // remove stack items
            Console.WriteLine("Stack item count:" + stackObj.Count); // count stack item
            Console.ReadKey();
        }
    }
}

Collections in C#

 

Queue

The Queue works like FIFO system, a first-in, first-out collection of Objects. Objects

stored in a Queue are inserted at one end and removed from the other. In queue,

we can add Enqueue (add) and dequeue (remove) from the queue.  Queue class is

under the System.Collections namespace.

 

Example

 

using System;
using System.Collections;
 
namespace QueueExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Queue queueObj = new Queue(); // create an object of Queue
            queueObj.Enqueue("Sunday"); // add element into queue
            queueObj.Enqueue("Monday");
            queueObj.Enqueue("Tuesday");
            queueObj.Enqueue("Wednesday");
            queueObj.Enqueue("Thursday");
            queueObj.Enqueue("Friday");
            queueObj.Enqueue("Saturday");
            foreach (string str in queueObj)
            {
                Console.WriteLine(str);     // print the queue data
            }
            queueObj.Dequeue();         // remove first element from queue
            queueObj.Dequeue();         // remove second element from queue
            Console.WriteLine("\nAfter dequeue");
            foreach (string str in queueObj)
            {
                Console.WriteLine(str);
            }
            Console.WriteLine("\n Queue element count :"+queueObj.Count);   // count queue element
            Console.WriteLine("\n Queue contains Friday (Some text) :" + queueObj.Contains("Friday")); // contains queue
            queueObj.Clear(); // remove all items from queue
            Console.WriteLine("\n Queue element count :" + queueObj.Count); // count queue element
            Console.ReadKey(); // hold the console screen
        }
    }
}

 

Output

Collections in C#


Updated 04-Feb-2020

Leave Comment

Comments

Liked By